<!-- 商品详情页面 -->
<template>
  <div class="goods-detail">
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      fixed
    />
    <div class="topimage-div borderBottom">
      <img :src="goodsInfo.IMAGE1" width="100%" onerror="this.src='http://cs-static-assets.oss-cn-beijing.aliyuncs.com/ds_system/errorimg.png'" />
    </div>
    <div class="goods-name">{{ goodsInfo.NAME }}</div>
    <div class="goods-price">¥{{ goodsInfo.PRESENT_PRICE | toMoney }}</div>
    <div class="tab-field">
      <van-tabs v-model="active" swipeable sticky>
        <!-- 将html字符串使用v-html进行转换为html代码 -->
        <van-tab title="商品详情"><div class="detail" v-html="goodsInfo.DETAIL" /></van-tab>
        <van-tab title="评论">
          <Comment />
        </van-tab>
      </van-tabs>
    </div>
    <van-goods-action>
      <van-goods-action-mini-btn icon="chat" text="客服" @click="onClient" />
      <van-goods-action-mini-btn icon="cart" text="购物车" @click="onShopCar" :info="currentGoodsCount" />
      <van-goods-action-big-btn text="加入购物车" @click="addShopCar" />
      <van-goods-action-big-btn text="立即购买" @click="handlePurchase" primary />
    </van-goods-action>
  </div>
</template>

<script>
import axios from 'axios';
import { Toast } from 'vant';
import requestUrl from '../../serverApi';
import toMoney from '../../filter/moneyFilter';
import Comment from '../../components/component/Comment';
import Bus from '../../bus';
export default {
  data () {
    return {
      // 使用‘$route’获取url上的参数
      goodsId: this.$route.query.goodsId,
      goodsInfo: {}, // 商品详细信息
      active: 0,
      currentGoodsCount: 0,
    };
  },
  // 引入组件
  components: {Comment},
  created() {
    this.getGoodsDetail();
    this.getCurrentGoodsCount();
  },
  methods: {
    getCurrentGoodsCount() {
      const goods = JSON.parse(localStorage.getItem('carInfo'));
      // 计算购物车的数量
      const goodsCount = goods.reduce((pre, curr, index, arr) => {
          return pre + curr.count;
      }, 0);
      this.currentGoodsCount = goodsCount;
    },
    onClickLeft() {
      // 返回上一级页面
      this.$router.go(-1);
    },
    onClient() {
      this.$router.push({name: 'Chat'})
    },
    onShopCar() {
      this.$router.push({name: 'ShopCar'});
    },
    handlePurchase() {
      this.$router.push({name: 'Purchase', query: {goodsId: this.goodsId}});
    },
    getGoodsDetail() {
      const detailUrl = `${requestUrl.goodsDetail}?goodsId=${this.goodsId}`;
      axios.get(detailUrl).then(res => {
        const data = res.data;
        // 查找不到数据的时候，data.message为null
        if (data.code === 200 && data.message) {
          this.goodsInfo = data.message;
        } else {
          Toast.fail('获取数据失败');
        }
      }).catch(err => {
        Toast.fail('获取数据失败');
      })
    },
    addShopCar() {
      // 添加购物车,信息都存在本地
      let carInfo = localStorage.getItem('carInfo');
      carInfo = carInfo ? JSON.parse(carInfo) : []; // 没有的话是null, 直接通过localStorage.carInfo获取得到的是undefined
      const findItem = carInfo.find((item) => item.goodsId === this.goodsId);
      if (!findItem) {
        // 没有在本地数据找到对应商品
        const newShopGoods = {
          goodsId: this.goodsInfo.ID,
          name: this.goodsInfo.NAME,
          price: this.goodsInfo.PRESENT_PRICE,
          image: this.goodsInfo.IMAGE1,
          count: 1,
        };
        carInfo.push(newShopGoods);
        localStorage.setItem('carInfo', JSON.stringify(carInfo));
        Toast.success('添加成功');
      } else {
        Toast.fail('该商品已在购物车中');
      }
      this.$router.push('/shopCar');
    },
  },
  filters: {
    toMoney(value) {
      return toMoney(value);
    }
  }
}
</script>
<style scoped>
  .topimage-div {
    padding-top: 46px;
    font-size: 0;
  }
  .goods-name,
  .goods-price {
    background-color: #fff;
    font-size: 14px;
    padding: 5px;
  }
  .goods-price {
    color: green;
  }
  .tab-field {
    margin-bottom: 50px;
  } 
  /*
    解决图片之间有空格的问题，即将img的父级元素的font-size设置为0px即可，
    解决方式有三种：
    1.将图片设置为float：left
    2.设置图片的父级元素的font-size为0
    3.将img标签依次排列中间不留间隙即可（写img代码时，标签之间不用换行，写为一行）
  */
  .detail {
    font-size: 0px;
  }
  
</style>
